//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Galleries.Components;

namespace CommunityServer.Galleries.Controls
{
    /// <summary>
    /// Summary description for CommentForum.
    /// </summary>
    public class CommentForm : GalleryThemedControl
    {
		#region Child Controls

        private TextBox tbTitle;
        private TextBox tbName;
        private TextBox tbComment;
        private TextBox tbUrl;
        private CheckBox chkRemember;
        private IButton btnSubmit;
        private PlaceHolder CommentFormWrapper;
        private ResourceControl DisabledMessage;
		private IButton addCommentlnk;
       
		#endregion

		#region Public Properties

        private GalleryPost _dataSource;
        
        /// <summary>
        /// Property DataSource (WeblogEntry)
        /// </summary>
        public GalleryPost DataSource
        {
            get
            {  return this._dataSource; }
            set
            {  this._dataSource = value; }
        }

		#endregion

		#region Skin

		protected override void AttachChildControls()
		{
			tbTitle = FindControl( "tbTitle" ) as TextBox;
			tbName = FindControl( "tbName" ) as TextBox;
			tbComment = FindControl( "tbComment" ) as TextBox;
			tbUrl = FindControl( "tbUrl" ) as TextBox;
			CommentFormWrapper = FindControl("CommentFormWrapper") as PlaceHolder;
			DisabledMessage = FindControl("DisabledMessage") as ResourceControl;

			InitializeChildControls();

		}

		private void InitializeChildControls()
		{
            IText Message = FindText("Message");
            if(Message != null)
            {
                Message.Visible = Context.Request.QueryString["CommentPosted"] != null;
            }

			addCommentlnk =  FindButton( "addCommentlnk" );
			if (addCommentlnk != null)
			{
				addCommentlnk.Click += new EventHandler(addComment_Clicked);
				addCommentlnk.CausesValidation = false;
			}

            if(Context.Request.IsAuthenticated)
            {
				if(tbName != null)
					tbName.Text = CurrentUser.DisplayName;
                HtmlGenericControl title = FindControl("NameTitle") as HtmlGenericControl;
				if(title != null)
					title.Visible = false;
                HtmlGenericControl desc = FindControl("NameDesc") as HtmlGenericControl;
				if(desc != null)
					desc.Visible = false;
				if(tbUrl != null)
					tbUrl.Text = CurrentUser.Profile.WebLog;
            }

            chkRemember = FindControl( "chkRemember" ) as CheckBox;
			if(chkRemember != null)
				chkRemember.Text = ResourceManager.GetString( "Weblog_CommentForm_RememberMe" );

            CheckCookie();
            
            btnSubmit = FindButton( "btnSubmit" );
			if(btnSubmit != null)
			{
				btnSubmit.Click +=new EventHandler(btnSubmit_Click);
				btnSubmit.Text = ResourceManager.GetString( "Submit" );
			}
        }


		#endregion

		#region Event Overrides

		protected override void OnLoad(System.EventArgs e)
		{
			base.OnLoad(e);
			if(!Page.IsPostBack)
				DataBind();
		}
		
		public override void DataBind()
		{
			base.DataBind();
			BindData();
		}

		#endregion

		private void BindData()
		{
            if(this.DataSource == null)
            {
                this.Visible = false;
                return;
            }
			else
            {
            	this.Visible = true;
            }


            if(CurrentGallery.EnableNewComments(DataSource,CurrentUser))
            {
				//the current user can add comments
                if(tbTitle != null)
                    tbTitle.Text = "re: " + Globals.HtmlDecode(DataSource.Subject);
				
				if(CommentFormWrapper != null)
					CommentFormWrapper.Visible = true;

				if(addCommentlnk != null)
					addCommentlnk.Visible = false;
			}
            else if(CurrentGallery.EnableNewComments(DataSource))
            {
            	//Somebody can add comments just not the current user
				if(CommentFormWrapper != null)
					CommentFormWrapper.Visible = false;

				if(addCommentlnk != null)
					addCommentlnk.Visible = true;

            }
			else
            {
				//Comments are disables so there is nothing to see here
                if(CommentFormWrapper == null)
                    this.Visible = false;
                else
                {
                    if(DisabledMessage != null)
                        DisabledMessage.Visible = true;

                    CommentFormWrapper.Visible = false;
					
					if(addCommentlnk != null)
						addCommentlnk.Visible = false;
				}

            }


			//Yes Show the form and Hide the Add Comment

			//No - are comments enabled
				
				//Yes Show The Add Comment link

				//No Hide the link and hide the comment form
        }

		//protected override void Authorize(Gallery g)
		//{
		//	base.Authorize (g);
		//	Permissions.AccessCheck(g,Permission.Reply,CurrentUser);
		//}



        private void CheckCookie()
        {
            if(!Page.IsPostBack)
            {
                HttpCookie user = Context.Request.Cookies["CommentUser"];
                if(user != null)
                {
					if(tbName != null)
						tbName.Text = user.Values["Name"];
					if(tbUrl != null)
						tbUrl.Text = user.Values["Url"];
                }
            }
        }

        protected string GetTitle()
        {
            if(tbTitle == null || Globals.IsNullorEmpty(tbTitle.Text))
                return "re: " + DataSource.Subject;


            return tbTitle.Text;
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if(!Page.IsValid || !CurrentGallery.EnableNewComments(DataSource, CurrentUser))
                return;

        	GalleryPost entry = new GalleryPost();
            entry.TitleUrl = tbUrl.Text;
            entry.Subject = GetTitle();
            entry.Body = tbComment.Text;
            entry.Excerpt = string.Empty;
            entry.IsApproved =  !CurrentGallery.IsPostModerated(DataSource,CurrentUser);
            entry.ParentID = DataSource.PostID;

            entry.PostType = PostContentType.HTML;
            entry.GalleryPostType = GalleryPostType.Comment;
            entry.SectionID = DataSource.SectionID;
            entry.UserTime = entry.PostDate = DateTime.Now;

            if (CurrentUser.IsAnonymous)
				entry.SubmittedUserName = tbName.Text;

			entry.User = CurrentUser;

			// Make sure the URL starts with http://
			if (!entry.TitleUrl.StartsWith("http://") && !entry.TitleUrl.StartsWith("https://"))
				entry.TitleUrl = "http://" + entry.TitleUrl;

			// If it is empty, set it to nothing
			if(entry.TitleUrl == "http://")
				entry.TitleUrl = string.Empty;

			if(chkRemember.Checked)
			{
				HttpCookie userCookie = new HttpCookie( "CommentUser" );
				userCookie.Values.Add("Name", tbName.Text);
				userCookie.Values.Add("Url", tbUrl.Text);
				Context.Response.SetCookie(userCookie);
			}

            //int postID = -1;
			GalleryPosts.CreateComment(DataSource.PostID, entry);
            //BlogPostResults result = WeblogPosts.Add(entry, CurrentUser, out postID);
            //if(result == BlogPostResults.Success &&  postID > 0)
            Context.Response.Redirect(string.Concat(GalleryUrls.Instance().ViewPicture(CurrentGallery.ApplicationKey, DataSource),"?CommentPosted=true") );



        }

		private void addComment_Clicked(object sender, EventArgs e)
		{
			//force the user to login
				base.Authorize (CurrentGallery);
				Permissions.AccessCheck(CurrentGallery,Permission.Reply,CurrentUser);
				CommentFormWrapper.Visible = true;
		}

    }
}
